package com.ouc.eddyAlgorithm.service.impl;

import com.ouc.common.utils.MathUtils;
import com.ouc.eddyAlgorithm.dao.OwDao;
import com.ouc.eddyAlgorithm.entity.WGridData;
import com.ouc.eddyAlgorithm.service.OwService;
import com.ouc.visualization.entity.ContourData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.NetcdfFile;

import java.io.IOException;
import java.math.BigDecimal;

@Service
public class OwServiceImpl implements OwService {

  @Autowired
  private OwDao owDao;

  @Override
  public ContourData<WGridData> getWContourData(String fileName) throws IOException, InvalidRangeException {
    NetcdfFile file = NetcdfFile.open(fileName);
    WGridData wGridData = owDao.getWGridData(file);
    ContourData<WGridData> contourData = new ContourData<>();
    if (wGridData == null) {
      return contourData;
    }

    float[] minAndMax = MathUtils.minAndMax(wGridData.getValues());
    float[] listLon = wGridData.getListLon();
    int lonLength = listLon.length;
    float lonInterval = BigDecimal.valueOf(listLon[1]).subtract(BigDecimal.valueOf(listLon[0])).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();//四舍五入保留两位小数
    float startLon = listLon[0];
    float[] listLat = wGridData.getListLat();
    int latLength = listLat.length;
    float latInterval = BigDecimal.valueOf(listLat[1]).subtract(BigDecimal.valueOf(listLat[0])).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();//四舍五入保留两位小数
    float startLat = listLat[0];
    contourData = new ContourData<>(wGridData, minAndMax[0], minAndMax[1],
        lonLength, latLength, lonInterval, latInterval, startLon, startLat, wGridData.getVariableName());

    return contourData;
  }
}
